package com.huaboot.system.controller;

import com.huaboot.commont.core.BaseResponse;
import com.huaboot.commont.core.ResultUtils;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.framework.log.annotations.OperateLog;
import com.huaboot.framework.log.enums.OperateTypeEnum;
import com.huaboot.system.service.SysObjectStoreService;
import com.huaboot.system.strategy.UploadStrategy;
import com.huaboot.system.strategy.context.UploadStrategyContextFactory;
import com.huaboot.system.vo.SysFileUploadVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("sys/file")
@Tag(name = "文件上传")
@AllArgsConstructor
public class SysFileUploadController {

    private final UploadStrategyContextFactory uploadStrategyContextFactory;
    private final SysObjectStoreService objectStoreService;
    @PostMapping("upload")
    @Operation(summary = "上传")
    @OperateLog(type = OperateTypeEnum.INSERT)
    public BaseResponse<SysFileUploadVO> upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BusinessException("请选择需要上传的文件");
        }

        //缓存中获取当前选择的文件上传
        String uploadStrategyName = objectStoreService.getCurrentStrategyName();

        UploadStrategy uploadStrategy = uploadStrategyContextFactory.getUploadStrategyServiceByMode(uploadStrategyName);

        String url = uploadStrategy.uploadFile(file,"ffdmw/");

        SysFileUploadVO vo = new SysFileUploadVO();
        vo.setUrl(url);
        vo.setSize(file.getSize());
        vo.setName(file.getOriginalFilename());
        vo.setPlatform("local");

        return ResultUtils.success(vo);
    }
}
